package server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.Charset;

import model.Keyword;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.google.appengine.api.ThreadManager;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class GetBing{
	String str = "";
	String domain = "www.google.com";
	String[] arr;
	int i = 0;
	public GetBing(Future future,String str,String domain,int i,String[] arr)
	{
		this.str = str;
		this.domain = domain;
		this.arr = arr;
		this.i = i;
		
		arr[i] = "";

		String query="";
		try {
			query = URLDecoder.decode(str,"UTF-8").trim().replaceAll("[ ]+", "+");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		HTTPResponse response;
		try {
			response = (HTTPResponse) future.get();
		
	        Document doc = Jsoup.parse(new String(response.getContent(),"utf-8"));
			
			Elements cite = doc.select(".sb_tlst");
			if(cite.size() > 0)
			{
				for (int j = 0; j < cite.size(); j++) {
					if(j < 10)
					{
						arr[i] += cite.get(j).select("a").attr("href").replaceAll("[ ]+", "")+" ";
					}
				}
			}
			
			if(arr[i] != "")
			{
				try {
					ObjectifyService.register(Keyword.class);
				} catch (Exception e) {
					// TODO: handle exception
				}
				Objectify objectify = ObjectifyService.begin();
				
				try {
					Keyword keyword = objectify.get(new Key<Keyword>(Keyword.class, query+domain));
				} catch (Exception e) {
					Keyword key = new Keyword();
					key.setKey(query+domain);
					key.setName(query);
					key.setResult(new Text(arr[i]));
					key.setDomain(domain);
					
					objectify.put(key);
				}
			}
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
//	public static void main(String[] args) throws IOException {
//		Content("gogo","www.google.com.vn");
//	}
}
